﻿using BarTender;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using ZXing;

namespace WindowsFormsApp10
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (s, a) =>
             {
                 btapp1 = new BarTender.Application();
             };
            worker.RunWorkerAsync();
        }

        private void btnPath_Click(object sender, EventArgs e)
        {

            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            //dialog.SelectedPath = path;
            //dialog.RootFolder = Environment.SpecialFolder.Programs;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text  = dialog.SelectedPath;
            }
        }

        private void btnListFile_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(textBox1.Text)) return;

            DirectoryInfo TheFolder = new DirectoryInfo(textBox1.Text);
            StringBuilder sb = new StringBuilder();
            //遍历文件夹
            foreach (DirectoryInfo NextFolder in TheFolder.GetDirectories())

            {
                sb.AppendLine(GetDir(NextFolder.FullName,1));
            }
            //遍历文件
            textBox2.Text = sb.ToString();
        }


        string GetDir(string dir,int level)
        {
            string space = string.Empty;
            if(level==2)
            {
                space = "  ";
            }
            else if(level == 3)
            {
                space = "    ";
            }
            else if(level == 4)
            {
                space = "      ";
            }
            else if (level == 5)
            {
                space = "        ";
            }
            StringBuilder sb = new StringBuilder();
            DirectoryInfo TheFolder = new DirectoryInfo(dir);
            foreach (DirectoryInfo NextFolder in TheFolder.GetDirectories())
            {
                sb.AppendLine(space + TheFolder.Name + "-" + NextFolder.Name);
                if(NextFolder.EnumerateDirectories().Any())
                {
                    sb.AppendLine(GetDir(NextFolder.FullName,level + 1));
                }
            }

            return sb.ToString();
        }

        private void btnTranFile_Click(object sender, EventArgs e)
        {
            try
            {
                string s = textBox1.Text;
                if (s.ToLower().EndsWith("btw"))
                {
                    Tran(s);
                }
                else
                {
                    TranFiles(s);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
            }
        }

        private void btnTranFileObject_Click(object sender, EventArgs e)
        {
            try
            {
                string s = textBox1.Text;
                if (s.ToLower().EndsWith("btw"))
                {
                    Tran(s, true);
                }
                else
                {
                    TranFiles(s, true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
            }
        }

        void TranFiles(string dir, bool isObject = false)
        {
            DirectoryInfo TheFolder = new DirectoryInfo(dir);

            try
            {
                var files = TheFolder.GetFiles();
                if(files != null && files.Length>0)
                foreach (FileInfo file in files)
                {
                    if (file.Name.ToLower().EndsWith("btw"))
                        Tran(file.FullName, isObject);
                }

                var dirs = TheFolder.GetDirectories();
                if(dirs!= null && dirs.Length>0)
                foreach (DirectoryInfo NextFolder in dirs)
                {
                    TranFiles(NextFolder.FullName, isObject);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
            }
        }

        BarTender.Application btapp1 = null;
        void Tran(string fileName, bool isObject=false)
        {
            if (!File.Exists(fileName)) return;
            string newfile = Path.GetDirectoryName(fileName) + "\\" + Path.GetFileNameWithoutExtension(fileName) + ".frx";
            if (File.Exists(newfile) && !checkBox1.Checked)
            {
                textBox3.Text = "\r\n" + fileName + "\r\n" + textBox3.Text;
                return;
            }
            StringBuilder sb = new StringBuilder();

            BarTender.Format btFormat1 = null;

            //BackgroundWorker worker = new BackgroundWorker();
            //worker.DoWork += (s, a) =>
            //    {
            try
            {
                #region
                if (btapp1 == null) return;
                btFormat1 = btapp1.Formats.Open(fileName, false, "");
                int i1 = btFormat1.Objects.Count;

                List<string> typeList = new List<string>();

                StringBuilder frx = new StringBuilder();
                string modelfile = AppDomain.CurrentDomain.BaseDirectory +  "textmode.txt";
                if(!isObject) modelfile = AppDomain.CurrentDomain.BaseDirectory + "textmode1.txt";
                //string modeltext = ReadTxt(modelfile);
                double pagewidth = btFormat1.PageSetup.LabelWidth;
                double pageheight = btFormat1.PageSetup.LabelHeight;
                StringBuilder valueText = new StringBuilder();

                string codeType = "QR Code";

                XmlDocument _XmlDocument = new XmlDocument();
                _XmlDocument.Load(modelfile);

                string pageName = "Report/ReportPage";
                XmlNode pageNode = _XmlDocument.SelectSingleNode(pageName);
                if (pageNode != null)
                {
                    pageNode.Attributes["PaperWidth"].Value = pagewidth.ToString();
                    pageNode.Attributes["PaperHeight"].Value = pageheight.ToString();
                }

                string nodeName = "Report/ReportPage/PageHeaderBand";
                if (isObject) nodeName = "Report/ReportPage/DataBand";
                XmlNode parentNode = _XmlDocument.SelectSingleNode(nodeName);
                if (parentNode == null)
                {
                    sb.AppendLine("没有节点：" + nodeName);
                    return;
                }

                XmlElement newnode = null;
                XmlElement newnode2 = null;
                List<XmlElement> txtBarNodes = new List<XmlElement>();
                List<XmlElement> lineNodes = new List<XmlElement>();

                int i = 0;

                foreach (DesignObject v in btFormat1.Objects)
                {
                    newnode2 = null;
                    i++;

                    string type = Microsoft.VisualBasic.Information.TypeName(v);

                    switch (v.Type)
                    {
                        case BtObjectType.btObjectBarcode:
                            #region
                            if (v.Height <= 0) codeType = "QR Code";
                            else codeType = "Code128";

                            newnode = _XmlDocument.CreateElement("BarcodeObject");
                            newnode.SetAttribute("Name", "Barcode" + i.ToString());
                            newnode.SetAttribute("AutoSize", "true");
                            newnode.SetAttribute("Barcode", codeType);
                            newnode.SetAttribute("Barcode.ErrorCorrection", "L");
                            newnode.SetAttribute("Barcode.Encoding", "UTF8");
                            newnode.SetAttribute("Barcode.QuietZone", "false");
                            newnode.SetAttribute("ShowText", "false");
                            newnode.SetAttribute("AutoShrink", "FontWidth");
                            //newnode.SetAttribute("AutoSize", "false");

                            //AutoSize="false"
                            if (v.Height > 0)
                            {
                                newnode2 = _XmlDocument.CreateElement("TextObject");
                                newnode2.SetAttribute("Name", "Text" + i.ToString());
                                newnode2.SetAttribute("Padding", "0, 0, 0, 0");
                                newnode2.SetAttribute("AutoShrink", "FontWidth");
                            }

                            #endregion
                            break;
                        case BtObjectType.btObjectBox:
                            #region
                            newnode = _XmlDocument.CreateElement("ShapeObject");
                            newnode.SetAttribute("Name", "Shape" + i.ToString());
                            newnode.SetAttribute("Shape", "RoundRectangle");
                            newnode.SetAttribute("Border.Width", Math.Round((v.LineThickness * 3.000), 2).ToString());
                            #endregion
                            break;
                        case BtObjectType.btObjectEllipse:
                            #region
                            newnode = _XmlDocument.CreateElement("ShapeObject");
                            newnode.SetAttribute("Name", "Shape" + i.ToString());
                            newnode.SetAttribute("Shape", "Ellipse");
                            newnode.SetAttribute("Border.Width", Math.Round((v.LineThickness * 3.000), 2).ToString());
                            #endregion
                            break;
                        case BtObjectType.btObjectLine:
                            #region
                            newnode = _XmlDocument.CreateElement("LineObject");
                            newnode.SetAttribute("Name", "Line" + i.ToString());
                            newnode.SetAttribute("Border.Width", Math.Round((v.LineThickness * 3.000), 2).ToString());
                            #endregion
                            break;
                        case BtObjectType.btObjectText:
                            #region
                            newnode = _XmlDocument.CreateElement("TextObject");
                            newnode.SetAttribute("Name", "Text" + i.ToString());
                            newnode.SetAttribute("Padding", "0, 0, 0, 0");
                            newnode.SetAttribute("AutoShrink", "FontWidth");
                            //AutoShrink="FontWidth"
                            break;
                        #endregion
                        case BtObjectType.btObjectRichText:
                            #region
                            newnode = _XmlDocument.CreateElement("RichObject");
                            newnode.SetAttribute("Name", "RichText" + i.ToString());
                            newnode.SetAttribute("Padding", "0, 0, 0, 0");
                            #endregion
                            break;
                        case BtObjectType.btObjectPicture:
                            #region
                            newnode = _XmlDocument.CreateElement("PictureObject");
                            newnode.SetAttribute("Name", "Picture" + i.ToString());
                            //newnode.SetAttribute("Image", v.Value);
                            #endregion
                            break;
                        case BtObjectType.btObjectShape:
                            #region
                            newnode = _XmlDocument.CreateElement("PictureObject");
                            newnode.SetAttribute("Name", "Shape" + i.ToString());
                            //newnode.SetAttribute("Image", v.Value);
                            newnode.SetAttribute("Shape", "Triangle");
                            newnode.SetAttribute("Border.Width", Math.Round((v.LineThickness * 3.000), 2).ToString());
                            #endregion
                            break;
                        default:
                            sb.AppendLine(v.Name + " aaaaaaaaa " + v.Type.ToString().ToString());
                            newnode = _XmlDocument.CreateElement(v.Type.ToString());
                            newnode.SetAttribute("Name", v.Type.ToString() + i.ToString());
                            MessageBox.Show("不支持的类型：" + v.Type.ToString());
                            sb.AppendLine("不支持的类型：" + v.Type.ToString());
                            sb.AppendLine(fileName);
                            break;
                    }

                    double width1 = 0; 
                    try { width1 = v.Width; }catch { }
                    double height1 = 0; 
                    try { height1 = v.Height; } catch { }

                    if(height1 == 0)  width1 = 100;
                        if (height1 == 0) width1 = 100;

                    bool isText = (v.Type == BtObjectType.btObjectText
                    || v.Type == BtObjectType.btObjectRichText);
                    if (isText)
                    {
                        try
                        {
                            //string textStr = "测试字体大小";
                            float fontsize = (float)(v.FontSize * v.FontScale / 100.000);
                            Font stringFont = new Font(v.FontName, fontsize);
                            Size sz = TextRenderer.MeasureText(v.Value, stringFont);
                            //MessageBox.Show(sz.Width + "," + sz.Height);
                            if (height1 <= 0) height1 = sz.Height;
                            if (width1 <= 0) width1 = sz.Width * 1.1;


                        }
                        catch (Exception exx) { }
                    }
                    else if(v.Type == BtObjectType.btObjectBox)
                    {
                        width1 *= 3.7800;
                        height1 *= 3.7800;
                    }
                    else
                    {
                        width1 *= 3.7800;
                        height1 *= 3.7800;
                    }

                    if (v.Type == BtObjectType.btObjectLine)
                    {
                        if (v.LineStartX != v.LineEndX)
                        {
                            width1 = Math.Abs((v.LineEndX - v.LineStartX)) * 3.7800;
                        }

                        if (v.LineStartY != v.LineEndY)
                        {
                            height1 = Math.Abs((v.LineEndY - v.LineStartY)) * 3.7800;
                        }
                    }


                    if (v.Type == BtObjectType.btObjectBox || v.Type == BtObjectType.btObjectEllipse
                        || v.Type == BtObjectType.btObjectLine || v.Type == BtObjectType.btObjectPicture
                        || v.Type == BtObjectType.btObjectShape)
                        lineNodes.Add(newnode);
                    else
                        txtBarNodes.Add(newnode);

                    if(newnode2 != null) txtBarNodes.Add(newnode2);

                    double left = v.X;
                    double top = v.Y;

                    if (v.Type == BtObjectType.btObjectBox)
                    {
                        left /= 10.00;
                        top /= 3.78;
                    }
                    else if (v.Type == BtObjectType.btObjectBarcode)
                    {
                        left *= 3.7800;
                        top *= 3.7800;
                    }
                    else if (v.Type == BtObjectType.btObjectLine)
                    {
                        if (width1 > 0) { top *= 3.78; left /= 3.78; }
                        if (height1 > 0) { top /= 6.667; left *= 3.78; }
                    }
                    else if (v.Type == BtObjectType.btObjectText || v.Type == BtObjectType.btObjectRichText)
                    {
                        if (v.Width == 0)
                        {
                            left *= 3.78;
                            top *= 3.78;
                        }
                        else
                        {
                            left *= 3.78;
                            top *= 3.78;
                        }
                    }
                    else
                    {
                        left *= 3.5500;
                        top *= 3.7800;
                    }

                    //try { newnode.SetAttribute("Name", v.Name); } catch { }
                    try { newnode.SetAttribute("Left", Math.Round(left, 4).ToString()); } catch { }
                    try { newnode.SetAttribute("Top", Math.Round(top, 4).ToString()); } catch { }
                    try { newnode.SetAttribute("Width", Math.Round(width1, 4).ToString()); }
                    catch { }
                    try { newnode.SetAttribute("Height", Math.Round(height1, 4).ToString()); } catch { }
                    try { newnode.SetAttribute("Text", v.Value); } catch { }
                    try
                    {
                        newnode.SetAttribute("Font", v.FontName + ", "
                      + Math.Round(v.FontSize * v.FontScale / 100.0, 1).ToString() + "pt"
                       + (v.FontBold ? ", style=Bold" : string.Empty)
                      );
                    }
                    catch { }

                    if(newnode2 != null)
                    {
                        float fontsize = (float)(v.FontSize * v.FontScale / 100.000);
                        Font stringFont = new Font(v.FontName, fontsize);
                        Size sz = TextRenderer.MeasureText(v.Value, stringFont);
                        //MessageBox.Show(sz.Width + "," + sz.Height);
                        if (height1 <= 0) height1 = sz.Height;
                        if (width1 <= 0) width1 = sz.Width * 1.1;

                        try { newnode2.SetAttribute("Left", Math.Round(left, 4).ToString()); } catch { }
                        try { newnode2.SetAttribute("Top", Math.Round(top+15d, 4).ToString()); } catch { }
                        try { newnode2.SetAttribute("Width", Math.Round(width1, 4).ToString()); }
                        catch { }
                        try { newnode2.SetAttribute("Height", Math.Round(height1, 4).ToString()); } catch { }
                        try { newnode2.SetAttribute("Text", v.Value); } catch { }
                        try
                        {
                            newnode2.SetAttribute("Font", v.FontName + ", "
                          + Math.Round(v.FontSize * v.FontScale / 100.0, 1).ToString() + "pt"
                           + (v.FontBold ? ", style=Bold" : string.Empty)
                          );
                        }
                        catch { }
                    }
                }

                lineNodes.ForEach(n =>
                {
                    parentNode.AppendChild(n);
                });
                lineNodes.Clear();

                txtBarNodes.ForEach(n =>
                {
                    parentNode.AppendChild(n);
                });
                txtBarNodes.Clear();

                //string newfile = Path.GetDirectoryName(fileName) + "\\" + Path.GetFileNameWithoutExtension(fileName) + ".frx";
                _XmlDocument.Save(newfile);

                //textBox2.Text = sb.ToString();
                #endregion
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
                sb.AppendLine(fileName);
                sb.AppendLine(ex.Message + "\r\n" + ex.StackTrace);
            }
            finally
            {
                try
                {
                    if (btFormat1 != null) btFormat1.Close();
                    //if (btapp1 != null) btapp1.Quit();
                }
                catch (Exception ex)
                {

                }
            }
            //};

            //worker.RunWorkerCompleted += (s, a) =>
            //    {

            textBox3.Text = "\r\n" + fileName + "\r\n" + textBox3.Text;
            if (sb.Length > 0) textBox2.Text = "\r\n" + sb.ToString() + "\r\n" + textBox2.Text;
            //    };

            //worker.RunWorkerAsync();
        }

        private void btnFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "BTW|*btw";
            //dialog.SelectedPath = path;
            //dialog.RootFolder = Environment.SpecialFolder.Programs;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = dialog.FileName;
            }
        }

        string ReadTxt(string file)
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                // 创建一个 StreamReader 的实例来读取文件 
                // using 语句也能关闭 StreamReader
                
                using (StreamReader sr = new StreamReader(file))
                {
                    string line;

                    // 从文件读取并显示行，直到文件的末尾 
                    while ((line = sr.ReadLine()) != null)
                    {
                        sb.Append(line);
                    }
                }
            }
            catch (Exception e)
            {
                // 向用户显示出错消息
                MessageBox.Show(e.Message);
            }


            return sb.ToString();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show(((int)dateTimePicker1.Value.DayOfWeek).ToString());
        }



        private void button5_Click(object sender, EventArgs e)
        {
            var writer = new BarcodeWriter
            {
                Format = BarcodeFormat.DATA_MATRIX
            };
            writer.Options.GS1Format = true;
            writer.Options.Height = 500;
            writer.Options.Width = 500;

            writer
                .Write(textBox4.Text)
                .Save(@"D:\barcode11.png");
            Process.Start(@"D:\barcode11.png");
        }
    }
}
